import { Button, Popconfirm, Tooltip } from 'antd';
import ProTable, { ActionType } from "@ant-design/pro-table";
import { PlusOutlined } from '@ant-design/icons';
import { ProColumns } from '@ant-design/pro-table';
import { PageContainer } from "@ant-design/pro-layout";
import BreadcrumbDept from '@/components/BreadcrumbDept';
import './style.less';
import EditForm from './EditForm';
import { useEffect, useRef, useState } from 'react';
import { getCurrentUserDept } from '@/services/user/login'
import * as subDpetApi from '@/services/permissions/subDeptApi'

const underlingDepartment = () => {

  const [loading, setLoading] = useState<boolean>(false);
  const [editFormOpen, setEditFormOpen] = useState<boolean>(false);
  const [subDept, setSubDept] = useState<PERMISSIONSAPI.SubDept>();
  const [deptOptions, setDeptOptions] = useState<Array<{ dept_code: string, dept_name: string }>>([]);
  const actionRef = useRef<ActionType>();

  const stateOptions = [
    { label: '已启用', value: 'R' },
    { label: '已停用', value: 'S' },
    { label: '已删除', value: 'D' }
  ];

  const columns: ProColumns<PERMISSIONSAPI.SubDept>[] = [
    {
      title: '所属业务科室',
      dataIndex: 'dept_code',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        options: deptOptions.map(({ dept_code, dept_name }) => ({
          label: <Tooltip title={`${dept_code}-${dept_name}`}>{dept_code}-{dept_name}</Tooltip>,
          value: dept_code
        })),
        showSearch: true,
        filterOption: true
      },
      ellipsis: true,
      colSize: 3,
      formItemProps: {
        labelCol: { flex: '0 0 96px' },
        wrapperCol: { style: { width: 'calc(100% - 96px)' } }
      }
    },
    {
      title: '所属业务科室',
      dataIndex: 'dept_name',
      search: false
    },
    {
      title: '部门编号',
      dataIndex: 'sub_dept_code',
      colSize: 2.5,
      formItemProps: {
        labelCol: { flex: '0 0 70px' },
        wrapperCol: { style: { width: 'calc(100% - 70px)' } }
      }
    },
    {
      title: '二级部门名称',
      dataIndex: 'sub_dept_name',
      colSize: 3,
      formItemProps: {
        labelCol: { flex: '0 0 92px' },
        wrapperCol: { style: { width: 'calc(100% - 92px)' } }
      }
    },
    {
      title: '管理员',
      dataIndex: 'manager_oper_name',
      search: false
    },
    {
      title: '地址',
      dataIndex: 'address',
      search: false
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        options: stateOptions,
        showSearch: true,
        filterOption: true
      },
      colSize: 2.5,
      formItemProps: {
        labelCol: { flex: '0 0 46px' },
        wrapperCol: { style: { width: 'calc(100% - 46px)' } }
      }
    },
    {
      title: '状态',
      search: false,
      renderText: (text, record) => stateOptions.find(e => e.value === record.status)?.label
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: '15%',
      render: (_, record, idx, action) => <>
        <div style={{ display: 'inline-flex', gap: 24 }}>
          {record.status !== 'D' && <a onClick={async () => { stateChange(record, action); }}>{record.status === 'R' ? '停用' : '启用'} </a>}
          {record.status === 'R' && <a onClick={() => { setSubDept(record); setEditFormOpen(true); }}>编辑</a>}
          {
            record.status !== 'D' &&
            <Popconfirm
              placement="topRight" title='确认删除？'
              onConfirm={async () => await deleteSubDept(record.sub_dept_code, action)}
            >
              <a>删除</a>
            </Popconfirm>
          }
        </div>
      </>
    }
  ];

  const deleteSubDept = async (code: string, action: any) => {
    setLoading(true);
    subDpetApi.deleteSubDept(code).finally(() => {
      action?.reload(true);
      setLoading(false);
    });
  };

  const stateChange = async ({ sub_dept_code, status }: PERMISSIONSAPI.SubDept, action: any) => {
    setLoading(true);
    await subDpetApi.editSubDept({ sub_dept_code, status: status == 'R' ? 'S' : 'R' }).finally(() => {
      action?.reload();
      setLoading(false);
    });
  };

  useEffect(() => {
    getCurrentUserDept().then((res: any) => {
      setDeptOptions((res.record_list || []).map(({ dept_code, dept_name }: any) => ({ dept_code, dept_name })));
    });
  }, []);

  return <>
    <PageContainer extra={<BreadcrumbDept />} breadcrumb={{}}>
      <ProTable<PERMISSIONSAPI.SubDept>
        actionRef={actionRef}
        rowKey="sub_dept_code"
        className='mytable'
        loading={loading}
        bordered
        search={{
          span: 2,
          collapsed: false,
          style: { padding: '0 8px' },
          optionRender: (_, __, [, query]) => [query]
        }}
        request={async (params) => {
          setLoading(true);
          try {
            const res = await subDpetApi.getSubDeptListByPage(params);
            return {
              data: res.record_list,
              success: true,
              total: res.sum_record_num
            };
          } catch (reason) {
            return { success: false, data: [] };
          } finally {
            setLoading(false);
          }
        }}
        options={false}
        columns={columns}
        toolBarRender={() => [
          <Button
            onClick={() => { setSubDept(undefined); setEditFormOpen(true); }}
            icon={<PlusOutlined />}
            type="primary">
            新增
          </Button>
        ]}
        pagination={{ showQuickJumper: true }}
        // form={{ wrapperCol: { style: { flexGrow: 0, flexShrink: 0, width: '100%' } } }}
      />
    </PageContainer>

    <EditForm open={editFormOpen} onOpenChange={setEditFormOpen} subDept={subDept} finishCallback={() => actionRef.current?.reload()} />
  </>;
};

export default underlingDepartment;
